from django.http import JsonResponse
from django.views import View

from .ai_fruits import fruit_model
from .ai_mnist_handwritten_num import handwritten_num_nn
from .ai_lenet_cnn import lenet_cnn
from tools import base64_to_cv_image
from tools.response_code import get_resp_dict
import requests
import paddle.dataset.image as pdi
import json
import base64


class HandwrittenNumView(View):
    """
    HandwrittenNumView视图：获取数字手写体识别的结果
    访问路由：/ai/handwritten_num
    """

    def post(self, request):
        model = request.POST.get('model')
        image_base64 = request.POST.get('image').split(',').pop()
        image = base64_to_cv_image(image_base64)
        image[image == 0] = 255
        if model == '0':
            result = handwritten_num_nn.recognize(image)
        else:
            result = lenet_cnn.recognize(image)

        return JsonResponse(get_resp_dict(int(result)))


class FruitView(View):
    """
    FruitView视图：获取水果图片识别的结果
    访问路由：/ai/fruit
    """

    def post(self, request):
        model = request.POST.get('model')
        image = request.FILES.get('image')
        img = image.read()

        if model == '0':
            result = fruit_model.recognize(img)
        elif model == '1':
            im_array = pdi.load_image_bytes(img)
            im_reshape = pdi.simple_transform(im_array, 128, 128, False)
            im_list = im_reshape.tolist()
            im_json = json.dumps(im_list)
            apiKey = '230d0541-71ec-4f71-8cce-acc4fa916bb2'
            url = 'https://aistudio.baidu.com/serving/online/6939?apiKey=%s' % apiKey
            resp = requests.post(url, json={'image': im_json}).json()
            if resp['errorCode'] == 0:
                result = resp['result']['name']
            else:
                print(resp)
                return JsonResponse(get_resp_dict(code=99999))
        else:
            im_base64 = base64.b64encode(img)
            apiKey = '869d5dbb-c760-4655-b923-11ae27ce4774'
            url = 'https://aistudio.baidu.com/serving/online/6947?apiKey=%s' % apiKey
            resp = requests.post(url, json={'image': im_base64}).json()
            if resp['errorCode'] == 0:
                result = resp['result']['name']
            else:
                print(resp)
                return JsonResponse(get_resp_dict(code=99999))

        return JsonResponse(get_resp_dict(result))
